<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>ELM 项目启动管理器</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
    }

    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      min-height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 20px;
    }

    .container {
      background: white;
      border-radius: 12px;
      box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
      max-width: 900px;
      width: 100%;
      overflow: hidden;
    }

    .header {
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white;
      padding: 30px;
      text-align: center;
    }

    .header h1 {
      font-size: 28px;
      margin-bottom: 10px;
    }

    .header p {
      font-size: 14px;
      opacity: 0.9;
    }

    .content {
      padding: 30px;
      display: grid;
      grid-template-columns: 1fr 1fr;
      gap: 30px;
      max-height: 500px;
      overflow-y: auto;
    }

    .section {
      display: flex;
      flex-direction: column;
      gap: 15px;
    }

    .section-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      display: flex;
      align-items: center;
      gap: 8px;
    }

    .service-item {
      background: #f8f9fa;
      border: 1px solid #e9ecef;
      border-radius: 8px;
      padding: 15px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      transition: all 0.3s ease;
    }

    .service-item:hover {
      border-color: #667eea;
      box-shadow: 0 4px 12px rgba(102, 126, 234, 0.1);
    }

    .service-info {
      flex: 1;
    }

    .service-name {
      font-weight: 600;
      color: #333;
      margin-bottom: 4px;
    }

    .service-status {
      font-size: 12px;
      color: #999;
      display: flex;
      align-items: center;
      gap: 6px;
    }

    .status-indicator {
      width: 8px;
      height: 8px;
      border-radius: 50%;
      background: #ccc;
      transition: all 0.3s ease;
    }

    .status-indicator.running {
      background: #10b981;
      box-shadow: 0 0 8px rgba(16, 185, 129, 0.5);
    }

    .service-actions {
      display: flex;
      gap: 8px;
    }

    button {
      padding: 8px 16px;
      border: none;
      border-radius: 6px;
      font-size: 12px;
      font-weight: 600;
      cursor: pointer;
      transition: all 0.3s ease;
      white-space: nowrap;
    }

    .btn-start {
      background: #10b981;
      color: white;
    }

    .btn-start:hover:not(:disabled) {
      background: #059669;
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
    }

    .btn-stop {
      background: #ef4444;
      color: white;
    }

    .btn-stop:hover:not(:disabled) {
      background: #dc2626;
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(239, 68, 68, 0.3);
    }

    .btn-open {
      background: #3b82f6;
      color: white;
    }

    .btn-open:hover:not(:disabled) {
      background: #2563eb;
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(59, 130, 246, 0.3);
    }

    button:disabled {
      opacity: 0.5;
      cursor: not-allowed;
    }

    .footer {
      background: #f8f9fa;
      padding: 20px 30px;
      border-top: 1px solid #e9ecef;
      display: flex;
      justify-content: space-between;
      align-items: center;
      font-size: 12px;
      color: #666;
    }

    .footer-actions {
      display: flex;
      gap: 10px;
    }

    .btn-all-start {
      background: #667eea;
      color: white;
      padding: 10px 20px;
    }

    .btn-all-start:hover:not(:disabled) {
      background: #5568d3;
    }

    .btn-all-stop {
      background: #f97316;
      color: white;
      padding: 10px 20px;
    }

    .btn-all-stop:hover:not(:disabled) {
      background: #ea580c;
    }

    .console {
      background: #1e1e1e;
      color: #d4d4d4;
      padding: 15px;
      border-radius: 6px;
      font-family: 'Courier New', monospace;
      font-size: 11px;
      max-height: 200px;
      overflow-y: auto;
      margin-top: 20px;
      display: none;
    }

    .console.active {
      display: block;
    }

    .console-line {
      margin: 2px 0;
      white-space: pre-wrap;
      word-break: break-all;
    }

    .console-line.error {
      color: #f48771;
    }

    .console-line.success {
      color: #89d185;
    }

    .loading {
      display: inline-block;
      width: 12px;
      height: 12px;
      border: 2px solid #f3f3f3;
      border-top: 2px solid #667eea;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }

    @keyframes spin {
      0% { transform: rotate(0deg); }
      100% { transform: rotate(360deg); }
    }

    @media (max-width: 768px) {
      .content {
        grid-template-columns: 1fr;
      }

      .header h1 {
        font-size: 24px;
      }
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <h1>🚀 ELM 项目启动管理器</h1>
      <p>一键启动后端和各个前端服务</p>
    </div>

    <div class="content">
      <!-- 后端服务 -->
      <div class="section">
        <div class="section-title">
          <span>⚙️ 后端服务</span>
        </div>
        <div id="backend-container"></div>
      </div>

      <!-- 前端服务 -->
      <div class="section">
        <div class="section-title">
          <span>🎨 前端服务</span>
        </div>
        <div id="frontends-container"></div>
      </div>
    </div>

    <div class="console" id="console"></div>

    <div class="footer">
      <div>
        <span id="status-text">就绪</span>
      </div>
      <div class="footer-actions">
        <button class="btn-all-start" onclick="startAllServices()">启动全部</button>
        <button class="btn-all-stop" onclick="stopAllServices()">停止全部</button>
      </div>
    </div>
  </div>

  <script>
    let servicesStatus = {};
    let isStartingAll = false;

    /**
     * 初始化界面
     */
    async function init() {
      const config = await window.electronAPI.getConfig();
      renderBackend(config.backend);
      renderFrontends(config.frontends);
      updateStatus();

      // 监听服务输出
      window.electronAPI.onServiceOutput((data) => {
        addConsoleLog(data.output, data.type === 'stderr' ? 'error' : 'info');
      });

      // 定期更新状态
      setInterval(updateStatus, 2000);
    }

    /**
     * 渲染后端服务
     */
    function renderBackend(backend) {
      const container = document.getElementById('backend-container');
      container.innerHTML = `
        <div class="service-item">
          <div class="service-info">
            <div class="service-name">${backend.name}</div>
            <div class="service-status">
              <span class="status-indicator" id="status-${backend.name}"></span>
              <span id="status-text-${backend.name}">未运行</span>
              <span id="port-${backend.name}" style="margin-left: 8px; color: #667eea;"></span>
            </div>
          </div>
          <div class="service-actions">
            <button class="btn-start" id="btn-start-${backend.name}" onclick="startService('${backend.name}', 'backend')">启动</button>
            <button class="btn-stop" id="btn-stop-${backend.name}" onclick="stopService('${backend.name}')" disabled>停止</button>
          </div>
        </div>
      `;
    }

    /**
     * 渲染前端服务
     */
    function renderFrontends(frontends) {
      const container = document.getElementById('frontends-container');
      container.innerHTML = frontends.map(frontend => `
        <div class="service-item">
          <div class="service-info">
            <div class="service-name">${frontend.name}</div>
            <div class="service-status">
              <span class="status-indicator" id="status-${frontend.name}"></span>
              <span id="status-text-${frontend.name}">未运行</span>
              <span id="port-${frontend.name}" style="margin-left: 8px; color: #667eea;"></span>
            </div>
          </div>
          <div class="service-actions">
            <button class="btn-start" id="btn-start-${frontend.name}" onclick="startService('${frontend.name}', 'frontend')">启动</button>
            <button class="btn-stop" id="btn-stop-${frontend.name}" onclick="stopService('${frontend.name}')" disabled>停止</button>
            <button class="btn-open" id="btn-open-${frontend.name}" onclick="openService('${frontend.name}')" disabled>打开</button>
          </div>
        </div>
      `).join('');
    }

    /**
     * 启动服务
     */
    async function startService(serviceName, serviceType) {
      const btn = document.getElementById(`btn-start-${serviceName}`);
      btn.disabled = true;
      btn.innerHTML = '<span class="loading"></span>';

      try {
        const result = await window.electronAPI.startService(serviceName, serviceType);
        if (result.success) {
          addConsoleLog(`✓ ${serviceName} 启动成功`, 'success');
        } else {
          addConsoleLog(`✗ ${serviceName} 启动失败: ${result.message}`, 'error');
        }
      } catch (err) {
        addConsoleLog(`✗ 错误: ${err.message}`, 'error');
      }

      setTimeout(updateStatus, 1000);
    }

    /**
     * 停止服务
     */
    async function stopService(serviceName) {
      const btn = document.getElementById(`btn-stop-${serviceName}`);
      btn.disabled = true;

      try {
        const result = await window.electronAPI.stopService(serviceName);
        if (result.success) {
          addConsoleLog(`✓ ${serviceName} 已停止`, 'success');
        } else {
          addConsoleLog(`✗ 停止失败: ${result.message}`, 'error');
        }
      } catch (err) {
        addConsoleLog(`✗ 错误: ${err.message}`, 'error');
      }

      setTimeout(updateStatus, 500);
    }

    /**
     * 打开服务
     */
    async function openService(serviceName) {
      const status = servicesStatus.frontends.find(f => f.name === serviceName);
      if (status && status.running) {
        await window.electronAPI.openUrl(status.url);
      }
    }

    /**
     * 启动全部服务
     */
    async function startAllServices() {
      isStartingAll = true;
      const config = await window.electronAPI.getConfig();

      // 先启动后端
      await startService(config.backend.name, 'backend');
      await new Promise(resolve => setTimeout(resolve, 3000));

      // 再启动前端
      for (const frontend of config.frontends) {
        await startService(frontend.name, 'frontend');
        await new Promise(resolve => setTimeout(resolve, 2000));
      }

      isStartingAll = false;
      updateStatus();
    }

    /**
     * 停止全部服务
     */
    async function stopAllServices() {
      const config = await window.electronAPI.getConfig();
      
      // 停止所有前端
      for (const frontend of config.frontends) {
        await stopService(frontend.name);
      }

      // 停止后端
      await stopService(config.backend.name);
      updateStatus();
    }

    /**
     * 更新服务状态
     */
    async function updateStatus() {
      servicesStatus = await window.electronAPI.getServicesStatus();

      // 更新后端状态
      const backendRunning = servicesStatus.backend.running;
      updateServiceUI(servicesStatus.backend.name, backendRunning, servicesStatus.backend.port);

      // 更新前端状态
      servicesStatus.frontends.forEach(frontend => {
        updateServiceUI(frontend.name, frontend.running, frontend.port);
      });
    }

    /**
     * 更新单个服务的 UI
     */
    function updateServiceUI(serviceName, running, port) {
      const indicator = document.getElementById(`status-${serviceName}`);
      const statusText = document.getElementById(`status-text-${serviceName}`);
      const portText = document.getElementById(`port-${serviceName}`);
      const startBtn = document.getElementById(`btn-start-${serviceName}`);
      const stopBtn = document.getElementById(`btn-stop-${serviceName}`);
      const openBtn = document.getElementById(`btn-open-${serviceName}`);

      if (running) {
        indicator.classList.add('running');
        statusText.textContent = '运行中';
        portText.textContent = `端口: ${port}`;
        startBtn.disabled = true;
        stopBtn.disabled = false;
        if (openBtn) openBtn.disabled = false;
      } else {
        indicator.classList.remove('running');
        statusText.textContent = '未运行';
        portText.textContent = '';
        startBtn.disabled = isStartingAll;
        stopBtn.disabled = true;
        if (openBtn) openBtn.disabled = true;
      }
    }

    /**
     * 添加控制台日志
     */
    function addConsoleLog(text, type = 'info') {
      const console = document.getElementById('console');
      console.classList.add('active');

      const line = document.createElement('div');
      line.className = `console-line ${type}`;
      line.textContent = text;

      console.appendChild(line);
      console.scrollTop = console.scrollHeight;

      // 限制日志行数
      if (console.children.length > 100) {
        console.removeChild(console.firstChild);
      }
    }

    // 初始化
    init();
  </script>
</body>
</html>
